<?php
namespace mobile\controllers;

use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\member\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use common\models\member\Member;
use zhongkefu\helpers\SwfiEmail;
use yii\captcha\Captcha;
use common\models\Setting\Setting;
use yii\captcha\CaptchaAction;
use common\models\adminlog\AdminLog;

/**
 * Site controller
 */
class AuthController extends Controller
{
    public $layout = 'auth';
    /**
     * @inheritdoc
     */
	 
	public function actions()
    {
		$setting = Setting::findBySql('SELECT value FROM setting where id in(52,53,54)')->asArray()->all();
		
    }
	
    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
		$parenttitle = '登陆';
		$view = Yii::$app->view;
		$view->params['title'] = $parenttitle;
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post())){
			$qiyong = Member::find()->where(['username'=>Yii::$app->request->post()['LoginForm']['username']])->asArray()->one()['qiyong'];
			if($qiyong ==1) {
				if($model->login()) {
					return $this->redirect('/member/info');
				}else{

					yii::$app->getSession()->setFlash('error','用户名或密码错误！');
					$setting = Setting::findBySql('SELECT value FROM setting where id = 51')->asArray()->all();
					$data = $setting[0]['value'];
					if(strstr($data,"2")){
						$yanzhengma = true;
					}else{
						$yanzhengma = false;
					}
					return $this->render('login', [
						'model' => $model,
						'yanzhengma' => $yanzhengma,
					]);
				}
			}else{
				yii::$app->getSession()->setFlash('error','该账号已被封停！');
				$setting = Setting::findBySql('SELECT value FROM setting where id = 51')->asArray()->all();
				$data = $setting[0]['value'];
				if(strstr($data,"2")){
					$yanzhengma = true;
				}else{
					$yanzhengma = false;
				}
				return $this->render('login', [
					'model' => $model,
					'yanzhengma' => $yanzhengma,
				]);
			}
        } 
        elseif(Yii::$app->user->identity)
        {
        	return $this->redirect('/member/info');
        }
        else {
			$setting = Setting::findBySql('SELECT value FROM setting where id = 51')->asArray()->all();
			$data = $setting[0]['value'];
			if(strstr($data,"2")){
				$yanzhengma = true;
			}else{
				$yanzhengma = false;
			}
            return $this->render('login', [
                'model' => $model,
				'yanzhengma' => $yanzhengma,
            ]);
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }



    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
		header("Content-type: text/html; charset=utf-8");
		$parenttitle = '用户注册';
		$view = Yii::$app->view;
		$view->params['title'] = $parenttitle;
		$adlog = new AdminLog();
        $user = new Member();
		if(Yii::$app->request->post())
		{
			$info = Yii::$app->request->post();
			$userusername = Member::find()->where(['username' => $info['SignupForm']['username']])->one();
			$userphone = Member::find()->where(['phone' => $info['SignupForm']['phone']])->one();
			$useremail = Member::find()->where(['email' => $info['SignupForm']['email']])->one();
			
			if($userusername)
			{
				yii::$app->getSession()->setFlash('error','用户名已注册');
			}
			elseif($userphone)
			{
				yii::$app->getSession()->setFlash('error','手机号已注册');
			}
			elseif($useremail)
			{
				yii::$app->getSession()->setFlash('error','邮箱已注册');
			}
			else
			{
				$user->username = $info['SignupForm']['username'];
				$user->setPassword($info['SignupForm']['password']);
				$user->generateAuthKey();
				$user->company = $info['SignupForm']['qiyename'];
				$user->xingming = $info['SignupForm']['xingming'];
				$user->work = $info['SignupForm']['zhiwu'];
				$user->phone = $info['SignupForm']['phone'];
				$user->email = $info['SignupForm']['email'];
				$user->ip = $adlog->real_ip();
				if ($user->save(false))
				{
					if (Yii::$app->getUser()->login($user))
					{
						return $this->redirect(['/member/info']);
					}
				}
				else
				{
					yii::$app->getSession()->setFlash('error','验证码错误');
				}
			}

		}
 		return $this->render('signup', [
			'model' => $user,
		]);


    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password was saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }
	
	//找回密码
	public function actionPartone(){
		$parenttitle = '忘记密码';
		$view = Yii::$app->view;
		$view->params['title'] = $parenttitle;
        if(Yii::$app->request->post()) {
			$setting = Setting::findBySql('SELECT value FROM setting where id = 51')->asArray()->all();
			$data = $setting[0]['value'];
			if(strstr($data,"4")){
				$value = Yii::$app->request->post()['verifyCode'];
				$result = $this->createAction('captcha')->validate($value, false);
			}else{
				$resutl = true;
			}
			if($result){
			   $uname = Yii::$app->request->post()['username'];
			   $email = Yii::$app->request->post()['email'];
			   $member =  Member::findOne(['username'=>$uname]);
			   if($member->username&&$member->id){
					$mailer = SwfiEmail::getEmail();
					$mail= $mailer->compose();
					$mail->setTo($email);
					$mail->setSubject("忘记密码找回");
					$host = "http://".$_SERVER['HTTP_HOST'].'/auth/parttwo/?id='.$member->id;
					//$mail->setTextBody('Test conten1231123t');
					$content = '<table border="0" cellpadding="0" cellspacing="0" width="100%" style="margin: 0 auto; padding: 0;max-width:612px;" class="container" align="center">
									<tbody><tr>
										<td align="center" valign="top">
											 
											<table border="0" cellpadding="0" cellspacing="0" style="margin: 0; padding: 0;width:100%;background:#f0f0f0;" class="100p">
												<tbody><tr>
													<td style="width:30%;padding:0 20px;" class="100p-red">
														<img src="https://www.oracleimg.com/us/assets/oracle-logo-email.jpg" style="">
													</td>
													<td style="width:70%;padding:0 20px;text-align:right;" valign="middle" class="100p-gray">
														<a href="#" style="font-family:Helvetica;font-weight:bold;font-size:12px;color:#1f4f82;text-decoration:none;" target="_blank">订阅</a> &nbsp; | &nbsp; <a href="#" style="font-family:Helvetica;font-weight:bold;font-size:12px;color:#1f4f82;text-decoration:none;" target="_blank">我的帐户</a> &nbsp; | &nbsp; <a href="#" style="font-family:Helvetica;font-weight:bold;font-size:12px;color:#1f4f82;text-decoration:none;" target="_blank">帮助</a>
													</td>
												</tr>
											</tbody></table>    
										</td>
									</tr><tr>
										<td style="padding:20px;">尊敬的'.$uname.'：</td>
									</tr><tr>
										<td style="padding:0 20px 20px;">您是否忘记了密码？</td>
									</tr><tr>
										<td style="padding:0;">
											<table border="0" cellpadding="0" width="100%" cellspacing="0" style="margin: 0; padding: 0;max-width:612px;border:1px solid #edf1f1;color:#5f5f5f;" class="container"><tbody><tr style="background:#edf1f1;">
										<td style="text-align: center; vertical-align: top; font-size: 0;padding:15px 0;"><div style="width: 300px; display: inline-block; vertical-align: middle;"><table width="80%" align="center"><tbody><tr>
														<td style="background:#1F4F82;padding:13px 0;" align="center"><a href="'.$host.'"  style="text-decoration:none;color:#fff;font-size:16px;font-weight:bold;display:block;text-align:center;" target="_blank">重设密码</a></td>
													</tr>
												</tbody></table>
											</div>
											
											<div style="width: 300px; display: inline-block; vertical-align: middle;" class="gray-small-text">
												<table width="100%">
													<tbody><tr>
														<td style="font-size:14px;vertical-align:middle;text-align:left;" class="gray-text-wrap">此链接有效期为一天，且只能使用一次。<a></a></td>
													</tr></tbody></table>
											</div></td>
									</tr></tbody></table>
										</td>
									</tr><tr>
										<td style="padding:20px 20px 0;">如果您不希望更改密码或并未请求更改密码，请忽略并删除该邮件。</td>
									</tr><tr>
										<td style="padding:16px 20px 25px;">谢谢！<br> 
										</td>
									</tr><tr>
										<td><img src="https://www.oracleimg.com/us/assets/footer-shadow-email.jpg" style="width:100%;"></td>
									</tr><tr>
										<td style="padding:10px 20px 0;" class="nopadding">
											<table border="0" cellpadding="0" cellspacing="0" style="margin: 0; padding: 0;width:100%;" class="footer-wrap">
												<tbody><tr>
													<td style="width:45%;font-size:10px;padding-bottom:10px;" class="full-width-center">版权所有 @ 2016，Oracle 和/或其子公司。<br> 保留所有权利。
													</td></tr></tbody></table></td></tr></tbody></table>';
				$mail->setHtmlBody($content);//发布可以带html标签的文本
				if($mail->send()){
					Yii::$app->session->setFlash('success', '邮件发送成功！');
				}else{
					Yii::$app->session->setFlash('error','邮件发送失败！');
				}
					
			   }else{
				   Yii::$app->session->setFlash('error', '无此用户名！');
			   }
			}else{
				Yii::$app->session->setFlash('error', '验证码错误！');
			}
        }
        return $this->render('partone');
	}
	public function actionParttwo(){
       
        if(Yii::$app->request->post()) {
		   $id = Yii::$app->request->post()['id'];	
		   $password = Yii::$app->request->post()['repassword'];
		   $model = Member::findOne(['id'=>$id]);
		   $model->setPassword($password);
		   $model->generateAuthKey();
		   if($model->save()){
			   Yii::$app->session->setFlash('success', '密码修改成功！');
		   }else{
			   Yii::$app->session->setFlash('success', '密码修改失败！');
		   }
		}
		$id = !empty(Yii::$app->request->get()['id'])?intval(Yii::$app->request->get()['id']):'';
		return $this->render('parttwo', [
            'id' => $id,
        ]);
	}
}
